In this tutorial we’ll cover the following topics:
There is no function for displaying maps in the base R functionality. To display a simple map, we use the ‘maps’ package.
library(maps)
For our examples we will be using Indiana air monitoring site locations.
monitors <- read.table(header=T, text='
monitorid lat long datum name
1 41.60668 -87.304729 WGS84 Gary-IITRI
2 39.811097 -86.114469 WGS84 Indpls-Washington-Park
3 39.749019 -86.186314 WGS84 Indpls-Harding-St.
4 38.013248 -87.577856 WGS84 Evansville-Buena-Vista
5 39.159383 -86.504762 WGS84 Bloomington
')
First, let’s create a simple Indiana map.
map(database = 'state', regions = 'indiana')
Now we can use our monitor lats and longs to add points to the map using the base points() function.
points(x = monitors$long, y = monitors$lat)
We can jazz it up a bit by making it a county map and changing the symbol type and color.
To make interactive Google maps, we can use the googleVis package.
library(googleVis)
We have to do some formatting first. The coordinates must be in the form lat:long so we need to create a data frame with a variable in that format.
google.location <- paste(monitors$lat, monitors$long, sep = ":")
monitors.google <- data.frame(monitors, google.location)
g.inter.map <- gvisMap(data = monitors.google, locationvar = "google.location",
tipvar = "name")
plot(g.inter.map)
Leaflet is another interactive map that can be created in R using the leafletR package.
library(leafletR)
The coordinates must first be converted to a GeoJSON file using the toGeoJSON() function.
leaf.data <- toGeoJSON(data = monitors[, -1], dest = tempdir(), name = "monitors")
And we create the map using the leaflet() function.
leaf.map <- leaflet(data = leaf.data, popup = "name", dest = tempdir())
browseURL(leaf.map)